package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"github.com/kataras/iris/v12"
)

func HspLogin(ctx iris.Context) {
	const targetUrl = "https://www.hspcn.com/Hsp/HspUserApply/admin"
	formjson := &map[string]string{}
	ctx.ReadBody(&formjson)
	str := ""
	index := 0
	for k, v := range *formjson {
		str += fmt.Sprintf("%s=%s", k, v)
		if index != len(*formjson)-1 {
			str += "&"
		}
		index++
	}

	req, err := http.NewRequest("POST", targetUrl, strings.NewReader(str))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		log.Println(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": err.Error()})
		return
	}

	// 带上 cookie
	cookies := ctx.Request().Cookies()
	for _, ck := range cookies {
		req.AddCookie(ck)
	}
	req.Header.Add("Origin", "https://www.hspcn.com")
	req.Header.Add("Referer", "https://www.hspcn.com/Hsp/HspUserApply/login")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30")

	fmt.Println("HEHEHE.......1")

	httpClient := &http.Client{}
	httpResp, err := httpClient.Do(req)
	if err != nil {
		log.Println(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": err.Error()})
		return
	}
	defer httpResp.Body.Close()

	hspResponse, _ := ioutil.ReadAll(httpResp.Body)

	var jsondata iris.Map
	json.Unmarshal(hspResponse, &jsondata)
	ctx.StopWithJSON(httpResp.StatusCode, jsondata)
}
